package com.hd.manager.shiro.token;


import com.hd.appcommon.constant.OrgMemberConstant;
import com.hd.appcommon.entity.OrgMember;
import com.hd.appcommon.entity.Privilege;
import com.hd.appcommon.entity.Teacher;
import com.hd.appcommon.entity.User;
import com.hd.hdxgddcommon.utils.tree.BaseTree;
import com.hd.hdxgddcommon.utils.tree.TreeSupport;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;


/**
 * Created by Administrator on 2018/10/26.
 * Description :  Token管理器
 */
@Component
public class TokenManager {

    private static TokenCache ASSIST = null;

    public static ThreadLocal<Claims> claimsThreadLocal = new ThreadLocal<>();

    @Autowired
    public void setTokenCache(TokenCache tokenCache) {
        ASSIST = tokenCache;
    }

    /**
     * 获取当前用户的 token
     *
     * @return token
     */
    public static User getToken() {
        Claims claims = claimsThreadLocal.get();
        String id = String.valueOf(claims.get("id"));
        return ASSIST.getOrgMemberById(id);
    }

    /**
     * 判断当前用户是否是超级管理员
     *
     * @return boolean
     */
//    public static boolean isRoot() {
//        return OrgMemberConstant.TYPE.ROOT == getToken().getOrgMemberType();
//    }

    /**
     * 判断当前用户是否是超级管理员
     *
     * @return boolean
     */
    public static boolean isRoot(OrgMember token) {
        return OrgMemberConstant.TYPE.ROOT == token.getOrgMemberType();
    }

    /**
     * 获取当前用户的 privilege 集合
     *
     * @return privilege 集合
     */
    public static Collection<Privilege> getTokenPrivileges() {
        return ASSIST.listPrivilegesById(getToken().getId());
    }

    /**
     * 获取当前管理员的 地址 集合
     *
     * @return 地址 集合
     */
//    public static List<Location> getTokenLocations() {
//        OrgMember token = getToken();
//        return isRoot(token) ? ASSIST.listAllLocation() : ASSIST.listLocationById(token.getOrgMemberId());
//    }

    /**
     * 获取当前用户的 privilege 树
     *
     * @return privilege 树
     */
    public static List<BaseTree> getTokenPrivilegeTree() {
        Collection<Privilege> privileges = getTokenPrivileges();
//        List<BaseTree> treeList = privileges.stream().map(Privilege::toBaseTree).collect(Collectors.toList());
        List<BaseTree> treeList = privileges.stream().map(Privilege::toBaseTree).collect(Collectors.toList());
        treeList.sort(Comparator.comparing(BaseTree::getId));
        return TreeSupport.listToTreeList(treeList);
    }

}
